package com.eight.cloud.redisson.utils;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.redisson.config.RedissonConfig;
import lombok.Data;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * redis订阅和发布工具
 *
 * @ClassName: RedisListenerUtils
 * @Author: TXC
 * @Date: 2024-10-11 09:49
 **/
@ConditionalOnMissingBean(RedisListenerUtils.class)
@AutoConfigureAfter(RedissonConfig.class)
@Data
public class RedisListenerUtils {
    @Resource
    private RedissonClient redissonClient;
    private static ConcurrentHashMap<String, RedisListenerActuator> actuators = new ConcurrentHashMap<>();

    /**
     * 创建订阅发布器
     * @param channel 频道
     * @return RTopic
     */
    public RedisListenerActuator createActuator(String channel) {
        RedisListenerActuator actuator = actuators.get(channel);
        if (ObjectUtil.isNull(actuator)) {
            RTopic topic = redissonClient.getTopic(channel, new SerializationCodec());
            actuator = new RedisListenerActuator(topic);
            actuators.put(channel, actuator);
        }
        return actuator;
    }

    /**
     * 关闭订阅发布器
     * @param channel 频道
     */
    public void closeListen(String channel) {
        actuators.get(channel).unsubscribe();
        actuators.remove(channel);
    }
}
